// API 配置 - Docker环境，使用相对路径通过nginx代理
const API_BASE_URL = '/api';

// 本地存储键
const TOKEN_KEY = 'mininote_token';
const USER_INFO_KEY = 'mininote_user_info';

// 公共函数
function getToken() {
    return localStorage.getItem(TOKEN_KEY);
}

function setToken(token) {
    localStorage.setItem(TOKEN_KEY, token);
}

function removeToken() {
    localStorage.removeItem(TOKEN_KEY);
}

function getUserInfo() {
    const userInfoStr = localStorage.getItem(USER_INFO_KEY);
    return userInfoStr ? JSON.parse(userInfoStr) : null;
}

function setUserInfo(userInfo) {
    localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo));
}

function removeUserInfo() {
    localStorage.removeItem(USER_INFO_KEY);
}

function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '';
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN');
}

// 检查是否已登录
function checkAuth() {
    const token = getToken();
    if (!token) {
        window.location.href = 'index.html';
        return false;
    }
    return true;
}

// API请求封装
function apiRequest(url, method, data, needAuth = true) {
    const headers = {
        'Content-Type': 'application/json'
    };
    
    if (needAuth) {
        const token = getToken();
        if (token) {
            headers['Authorization'] = `Bearer ${token}`;
        }
    }
    
    const requestOptions = {
        method: method,
        headers: headers
    };
    
    if (data && (method === 'POST' || method === 'PUT')) {
        requestOptions.body = JSON.stringify(data);
    }
    
    return fetch(`${API_BASE_URL}${url}`, requestOptions)
        .then(response => {
            if (!response.ok) {
                if (response.status === 401) {
                    // 未授权，清除本地存储并跳转到登录页
                    removeToken();
                    removeUserInfo();
                    window.location.href = 'index.html';
                }
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.code !== 200) {
                throw new Error(data.message || '请求失败');
            }
            return data.data;
        });
}
